// pages/my/history/list.js

const app = getApp();
const util = require("../../../utils/util");
const requestUtil = require("../../../utils/request");
const api = require("../../../config/api");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    hasNoMoreSeen: false, // 没有更多记录
    hasSeenList: false, // 判断是否有历史记录
    userType: 1,
    cardInfo: null,
    fyNum: 1, // 页码
    fySize: 10, // 每页展示数
    seenList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let cardInfo = app.globalData.employeeInfo;
    this.setData({
      userType: 1,
      cardInfo
    })
    this.getSeenList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.hasNoMoreSeen) {
      this.getSeenList();
    }
  },

  /**
   * 获取历史记录列表
   */
  getSeenList: async function (id) {
    let params = {
      userType: 1,
      fySize: this.data.fySize,
      fyNum: this.data.fyNum,
      userId: this.data.cardInfo.id
    };
    let res = await requestUtil.request("POST", api.urls.getDistinctHistoryList, params);
    if (res.data.code != 0) {
      util.showToast(res.data.msg);
      return;
    }
    let seenList = res.data.data.rows;
    // 格式化日期
    for (let i = 0; i < seenList.length; i++) {
        let arr = util.formatChineseDate(new Date(seenList[i].createTime.replace(/-/g, '/'))).split('-');
        let time = {
          year: arr[0],
          month: arr[1],
          day: arr[2]
        }
        seenList[i].visitedDate = time;
    }
    let list = this.data.seenList;
    list.push(...seenList);

    let hasNoMore = this.data.hasNoMoreSeen;
    if(params.fyNum * params.fySize >= res.data.data.total) {
        hasNoMore = true;
    }
    this.setData({
      total: res.data.data.total,
      seenList: list,
      hasSeenList: true,
      hasNoMoreSeen: hasNoMore,
    })
  },
  /**
   * 打电话
   */
  onCall: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
    })
  },
  
  saveCard: function (e) {
    let idx = e.currentTarget.dataset.type;
    let cardInfo = this.data.seenList[idx];
    wx.addPhoneContact({
      firstName: cardInfo.custName,
      mobilePhoneNumber: cardInfo.custPhone,
      organization: cardInfo.custCompanyName,
      workAddressStreet: cardInfo.custCompanyAddr,
      email: cardInfo.custEmail,
      success: () => {
        wx.showToast({
          title: '添加成功',
        })
      },
      fail: (e) => {
        console.log("添加失败，原因为：" + e.errMsg);
      }
    })
  },
  /**
   * 复制到剪切板
   */
  copyData: function (o) {
    let val = o.currentTarget.dataset.val
    wx.setClipboardData({
      data: val
    })
  },
})